package com.example.qa_back.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.qa_back.entity.QA;
import com.example.qa_back.mapper.BackQAMapper;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author 董帅
 * @date 2021/3/6 - 18:01
 */
@Service
public class BackQAService {
    private final BackQAMapper backQAMapper;

    public BackQAService(BackQAMapper backQAMapper) {
        this.backQAMapper = backQAMapper;
    }

    /*
    * 功能：分页获取QA对
    * param：page，页数，最小为1；num，每页的个数
    * return：objectPage，每页内容
    * */
    public Page<QA> getPage(Integer page, Integer num) {
        Page<QA> objectPage = new Page<>(page, num);
        backQAMapper.selectPage(objectPage, null);
        return objectPage;
    }

    /*
    * 功能：根据id获取单个QA对
    * */
    public QA getOneQA(Integer id) {
        return backQAMapper.selectById(id);
    }

    /*
    * 功能：更新QA对
    * param：q_a，Q_A实体对象
    * return：0，更新失败；1，更新成功
    * */
    public Integer updateQA(QA QA) {
        int update = backQAMapper.updateById(QA);
        if (update == 1) {
            return 1;
        } else {
            return 0;
        }
    }
    /*
    * 功能：新增QA对，单个添加
    * param：q_a，Q_A实体对象
    * return：0，添加失败；1，添加成功
    * */
    public Integer insertQA(QA QA) {
        int insert = backQAMapper.insert(QA);
        if (insert == 1) {
            return 1;
        } else {
            return 0;
        }
    }
    /*
    * 功能：新增QA对，批量添加
    * param：q_as，Q_A实体对象
    * return：0，添加失败；1，添加成功
    * */
    public Integer insertManyQA(List<QA> qaList) {
        int insert = 0;
        for (QA QA : qaList) {
            insert = backQAMapper.insert(QA);
            if (insert != 1) {
                return 0;
            }
        }
        return 1;
    }
    /*
    * 功能：删除QA对，单个删除
    * param：id，QA对的id
    * return：0，删除失败；1，删除成功
    * */
    public Integer deleteQA(Integer id) {
        int i = backQAMapper.deleteById(id);
        if (i == 1) {
            return 1;
        } else {
            return 0;
        }
    }
    /*
    * 功能：删除QA对，批量删除
    * param：ids，QA对的id
    * return：0，删除失败；1，删除成功
    * */
    public Integer deleteManyQA(Integer[] ids) {
        int i = backQAMapper.deleteBatchIds(Arrays.asList(ids));
        if (i != 0) {
            return 1;
        } else {
            return 0;
        }
    }
    /*
    * 功能：返回所有QA对
    * */
    public List<QA> getAllQA() {
        QueryWrapper<QA> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("id");
        return backQAMapper.selectList(wrapper);
    }
    /*
    * 功能：模糊查询
    * param：问题
    * return：模糊查询到的QA对象
    * */
    public List<QA> search(String question) {
        QueryWrapper<QA> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(true, "question", question);
        return backQAMapper.selectList(queryWrapper);
    }
}
